package system.service.sys.impl;

import lombok.Getter;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import system.entity.SysRolePermission;
import system.mapper.SysRolePermissionMapper;
import system.service.sys.SysConfigService;
import system.service.sys.SysRolePermissionService;

@Service
public class SysRolePermissionServiceImpl implements SysRolePermissionService {
    @Autowired
    @Getter
    private SysRolePermissionMapper mapper;
    @Lazy
    @Autowired
    private SysConfigService configService;

    @Override
    public Integer add(SysRolePermission param) {
        Integer rows = SysRolePermissionService.super.add(param);
        configService.updateConfigVersion();
        return rows;
    }

    @Override
    public Integer update(SysRolePermission param) {
        Integer rows = mapper.update(param);
        configService.updateConfigVersion();
        return rows;
    }

    @Override
    public Integer deleteById(Integer id) {
        Integer rows = SysRolePermissionService.super.deleteById(id);
        configService.updateConfigVersion();
        return rows;
    }

    /*
     * 更新权限列表
     * @param roleId
     * @param permissionIds
     * @return
     */
    @Override
    @Transactional
    public int updateRolePermissions(Integer roleId, String[] permissionIds) {
        int rows = 0;
        //删除权限
        SysRolePermission deleteParam = new SysRolePermission();
        deleteParam.setRoleId(roleId);
        rows += mapper.delete(deleteParam);
        //添加权限
        for (String permissionId : permissionIds) {
            if (StringUtils.isNotBlank(permissionId)) {
                SysRolePermission rolePermission = new SysRolePermission();
                rolePermission.setRoleId(roleId);
                rolePermission.setPermissionId(permissionId);
                rows += mapper.add(rolePermission);
            }
        }
        //
        configService.updateConfigVersion();
        return rows;
    }
}